package com.xfdmao.fcat.coin.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xfdmao.fcat.coin.base.entity.KlineInfo;
import com.xfdmao.fcat.coin.base.entity.Matrix;
import com.xfdmao.fcat.coin.base.util.KlineInfoUtil;
import com.xfdmao.fcat.coin.base.util.StrategyUtil;
import com.xfdmao.fcat.coin.entity.Kline;
import com.xfdmao.fcat.coin.huobi.contract.api.HbdmClient;
import com.xfdmao.fcat.coin.huobi.contract.api.HbdmRestApiV1;
import com.xfdmao.fcat.coin.huobi.contract.api.IHbdmRestApi;
import com.xfdmao.fcat.coin.huobi.util.KlineUtil;
import com.xfdmao.fcat.coin.service.KlineService;
import com.xfdmao.fcat.common.controller.BaseController;
import com.xfdmao.fcat.common.util.JsonUtil;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * Created by fier on 2018/10/22
 */
@RestController
@RequestMapping("v1/kline")
public class KlineController extends BaseController<KlineService,Kline,Long>{
    private static Logger logger = Logger.getLogger(KlineController.class);

    @GetMapping(value = "/queryLine")
    public JSONObject queryLine() {

            /**
             * get请求无需发送身份认证,通常用于获取行情，市场深度等公共信息
             */
            IHbdmRestApi futureGetV1 = new HbdmRestApiV1(HbdmClient.url_prex);
            IHbdmRestApi futurePostV1 = new HbdmRestApiV1(HbdmClient.url_prex, HbdmClient.api_key, HbdmClient.secret_key);

            String[] coinNames = {"BTC","LTC","ETH","EOS","BCH","TRX","XRP"};
            String[] periods = {"5min", "15min","60min","4hour","1day"};
            for(int i=0;i<coinNames.length;i++){
                String coinName = coinNames[i];
                for(int j=0;j<periods.length;j++){
                    String period = periods[j];
                    while(true){
                        try{
                            // 获取K线数据
                            String historyKline = futureGetV1.futureMarketHistoryKline(coinName+"_CQ", period,2000+"");
                            logger.info("获取K线数据" + historyKline);
                            JSONObject jsonObject = JSONObject.parseObject(historyKline);
                            JSONArray jsonArray = jsonObject.getJSONArray("data");
                            List<com.xfdmao.fcat.coin.huobi.globle.response.Kline> klines = jsonArray.toJavaList(com.xfdmao.fcat.coin.huobi.globle.response.Kline.class);
                            KlineUtil.sort(klines);
                            klines.remove(0);//移除第一个未收盘的K先
                            List<Kline> kLineList = KlineUtil.toTableKline(klines);
                            for(Kline kline:kLineList){
                                kline.setSymbol(coinName);
                                kline.setContractType("quarter");
                                kline.setPeriod(period);
                            }
                            baseServiceImpl.insertBatch(kLineList);
                            break;
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                }
            }
        return JsonUtil.getSuccessJsonObject();
    }

    /**
     * 涨跌策略
     * @param symbol
     * @param contractType
     * @param period
     */
    @GetMapping(value = "/queryUpDownStrategy")
    public void queryUpDownStrategy( @RequestParam("symbol") String symbol, @RequestParam("contractType") String contractType,@RequestParam("period") String period ){
        List<Kline> kLineList = baseServiceImpl.queryList(symbol,contractType,period);
        List<KlineInfo> kLines = KlineInfoUtil.getKLines(kLineList);
        //Collections.reverse(kLines);
        Map<Date,KlineInfo> kLineMap = KlineInfoUtil.getKLineMap(kLines);
        Map<Date,Double> avgMap20 =  KlineInfoUtil.getAvg(kLines,20);
        Map<Date,Double> avgMap10 =  KlineInfoUtil.getAvg(kLines,10);
        Map<Date,Double> avgMap5 =  KlineInfoUtil.getAvg(kLines,5);
        List<Double> gain = KlineInfoUtil.dealGain(kLines);
        System.out.println(gain);
        StrategyUtil.strategyUpDown(kLines,avgMap5,avgMap10,avgMap20);
        StrategyUtil.strategyAvgAll(kLines);
    }

    /**
     * 涨跌策略
     * @param symbol
     * @param contractType
     * @param period
     */
    @GetMapping(value = "/queryMaStrategy")
    public void queryUpDownStrategy( @RequestParam("symbol") String symbol, @RequestParam("contractType") String contractType,
                                     @RequestParam("period") String period ,@RequestParam("upMaNum") Integer upMaNum ){
        List<Kline> kLineList = baseServiceImpl.queryList(symbol,contractType,period);
        List<KlineInfo> kLines = KlineInfoUtil.getKLines(kLineList);
        StrategyUtil.strategyAvg(kLines,upMaNum);
    }

    /**
     * 两条均线策略
     * @param symbol
     * @param contractType
     * @param period
     */
    @GetMapping(value = "/queryTwoMaStrategy")
    public JSONObject queryUpDownStrategy( @RequestParam("symbol") String symbol, @RequestParam("contractType") String contractType,
                                     @RequestParam("period") String period ,@RequestParam("upMaNum") Integer upMaNum ,@RequestParam("downMaNum") Integer downMaNum){
        List<Kline> kLineList = baseServiceImpl.queryList(symbol,contractType,period);
        List<KlineInfo> kLines = KlineInfoUtil.getKLines(kLineList);
        KlineInfoUtil.dealGain(kLines);
        List<KlineInfo> result = StrategyUtil.strategyTwoAvg(kLines,upMaNum,downMaNum);
        KlineInfoUtil.print(result,upMaNum,KlineInfoUtil.getAvg(kLines,upMaNum),downMaNum,KlineInfoUtil.getAvg(kLines,downMaNum));
        double income = KlineInfoUtil.getSumIncomeRate(result);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("income",income);
        jsonObject.put("sumNum",result.size());
        jsonObject.put("detail",result);
        return JsonUtil.getSuccessJsonObject(jsonObject);
    }

    /**
     * 求两天均线策略的最佳值
     * @param symbol
     * @param contractType
     * @param period
     */
    @GetMapping(value = "/queryTwoMaStrategyBest")
    public JSONObject queryTwoMaStrategyBest( @RequestParam("symbol") String symbol, @RequestParam("contractType") String contractType,@RequestParam("period") String period ,@RequestParam("maxMA") Integer maxMA){
        List<Kline> kLineList = baseServiceImpl.queryList(symbol,contractType,period);
        List<KlineInfo> kLines = KlineInfoUtil.getKLines(kLineList);
        KlineInfoUtil.dealGain(kLines);
        Matrix matrix = StrategyUtil.queryTwoMaStrategyBest(kLines,maxMA);
        return JsonUtil.getSuccessJsonObject(matrix);
    }

    @GetMapping(value = "/queryKlineInfo")
    public JSONObject queryKlineInfo( @RequestParam("symbol") String symbol, @RequestParam("contractType") String contractType,@RequestParam("period") String period ){
        List<Kline> kLineList = baseServiceImpl.queryList(symbol,contractType,period);
        return JsonUtil.getSuccessJsonObject(kLineList);
    }
}
